#!/usr/bin/env python
# encoding: utf-8
'''
@author: caopeng
@license: (C) Copyright 1999-2017, Fiberhome Telecommunication Technologies Co.,LTD.
@contact: gjzuo@fiberhome.com
@software: garner
@file: ip.py.py
@time: 2018/2/8 16:36
@desc:
'''

import socket, struct, fcntl

def get_ip(iface = 'eth0'):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sockfd = sock.fileno()
    SIOCGIFADDR = 0x8915

    ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
    try:
        res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
    except:
        return None

    ip = struct.unpack('16sH2x4s8x', res)[2]
    return socket.inet_ntoa(ip)

if __name__ == '__main__':
    print get_ip("br-ex")

